package com.icesoft.xsnow.oauth.service;

import cn.hutool.core.util.ArrayUtil;
import com.icesoft.xsnow.common.core.constant.SecurityConstants;
import com.icesoft.xsnow.common.security.dto.XSnowUser;
import com.icesoft.xsnow.framework.api.reponses.R;
import com.icesoft.xsnow.upms.api.dto.UserInfo;
import com.icesoft.xsnow.upms.api.po.SysUser;
import com.icesoft.xsnow.upms.api.remote.RemoteUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;

/**
 * @program: xsnow
 * @description: 用户服务
 * @author: xuefeng.gao
 * @create: 2019-05-10 14:57
 **/
@Service
@Slf4j
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final RemoteUserService remoteUserService;

    private final Map<String, XSnowUser> cache = new HashMap<>();


    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        XSnowUser user = cache.get(username.toLowerCase());
        if (cache != null && cache.get(username) != null) {
            return cache.get(username);
        }
        R<UserInfo> result = remoteUserService.info(username, SecurityConstants.FROM_IN);
        UserDetails userDetails = getUserDetails(result);

        return userDetails;
    }

    public void createUser(XSnowUser user) {
        Assert.isTrue(!userExists(user.getUsername()), "user should not exist");
        cache.put(user.getUsername().toLowerCase(), user);
    }


    public boolean userExists(String username) {
        return cache.containsKey(username.toLowerCase());
    }

    /**
     * 构建userdetails
     *
     * @param result 用户信息
     * @return
     */
    private UserDetails getUserDetails(R<UserInfo> result) {
        if (result == null || result.getStatus() == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserInfo info = result.getResult();
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(roleId -> dbAuthsSet.add(SecurityConstants.ROLE + roleId));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));
        }
        Collection<? extends GrantedAuthority> authorities
                = AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
        SysUser user = info.getSysUser();
        // 构造security用户
        return new XSnowUser(user.getId(),user.getUsername(),user.getPassword(),
                null,user.getPhone(),user.getEmail(),authorities);
    }

}
